"use client";

import { Share2Icon } from "lucide-react";
import { useState, useEffect } from "react";
import dynamic from 'next/dynamic';
import Image from "next/image";
import { getImageUrl } from "@/lib/utils";
import { CopyButton } from "@/components/ui/copy-button";

// 动态导入React Markdown和相关插件，减少初始加载体积
const ReactMarkdown = dynamic(() => import('react-markdown'), {
  ssr: false,
  loading: () => <div className="animate-pulse bg-white/5 h-96 rounded-md my-4"></div>
});

type BlogContentProps = {
  post: {
    title: string;
    description: string;
    publishedAt: string;
    updatedAt: string;
    category: string;
    content: string;
    bg_image?: {
      url: string;
      width: number;
      height: number;
      formats?: {
        small?: {
          url: string;
          width: number;
          height: number;
        };
        medium?: {
          url: string;
          width: number;
          height: number;
        };
        thumbnail?: {
          url: string;
          width: number;
          height: number;
        };
      };
    };
  };
};

export function BlogContent({ post }: BlogContentProps) {
  const [plugins, setPlugins] = useState<any[]>([]);
  const [pluginsLoaded, setPluginsLoaded] = useState(false);
  
  // 加载插件
  useEffect(() => {
    const loadPlugins = async () => {
      try {
        const [rehypeSlug, rehypeAutolinkHeadings, rehypePrismPlus] = await Promise.all([
          import('rehype-slug').then(mod => mod.default),
          import('rehype-autolink-headings').then(mod => mod.default),
          import('rehype-prism-plus').then(mod => mod.default)
        ]);
        
        setPlugins([
          [rehypeSlug, {
            slugify: (text: string) => text
              .toLowerCase()
              .trim()
              .replace(/\s+/g, '-')
              .replace(/[^\w\u4e00-\u9fa5-]/g, '')
              .replace(/^-+|-+$/g, '')
          }],
          [rehypeAutolinkHeadings, { behavior: 'wrap' }],
          [rehypePrismPlus, { ignoreMissing: true }]
        ]);
        setPluginsLoaded(true);
      } catch (error) {
        console.error('加载Markdown插件失败:', error);
        // 即使加载失败也标记为已加载，使用空插件列表
        setPluginsLoaded(true);
      }
    };
    
    loadPlugins();
  }, []);
  
  // 使用优化的图片URL - 优先使用中等大小或小尺寸的图片以减少加载时间
  const getOptimizedImageUrl = () => {
    if (!post.bg_image) return '';
    
    if (post.bg_image.formats?.medium?.url) {
      return getImageUrl(post.bg_image.formats.medium.url);
    }
    
    if (post.bg_image.formats?.small?.url) {
      return getImageUrl(post.bg_image.formats.small.url);
    }
    
    return getImageUrl(post.bg_image.url);
  };

  return (
    <article className="prose prose-invert prose-base max-w-none prose-headings:font-bold prose-h1:text-xl sm:prose-h1:text-4xl prose-h1:mb-3 sm:prose-h1:mb-6 prose-h2:text-lg sm:prose-h2:text-2xl prose-h2:mt-8 sm:prose-h2:mt-12 prose-h2:mb-4 sm:prose-h2:mb-6 prose-h3:text-base sm:prose-h3:text-xl prose-h3:mt-6 sm:prose-h3:mt-8 prose-h3:mb-3 sm:prose-h3:mb-4 prose-h4:text-sm sm:prose-h4:text-lg prose-h4:mt-6 sm:prose-h4:mt-8 prose-h4:mb-2 sm:prose-h4:mb-3 prose-p:leading-6 sm:prose-p:leading-7 prose-p:mb-4 sm:prose-p:mb-6 prose-a:text-emerald-400 hover:prose-a:text-emerald-300 prose-a:no-underline hover:prose-a:underline prose-strong:text-emerald-400 prose-code:text-emerald-300 prose-code:before:content-none prose-code:after:content-none prose-pre:bg-white/[0.03] prose-pre:border prose-pre:border-white/10 prose-img:rounded-xl prose-img:shadow-lg">
      {post.bg_image && (
        <div className="mb-8 -mx-4 sm:mx-0 sm:rounded-2xl overflow-hidden relative aspect-video">
          <Image 
            src={getOptimizedImageUrl()}
            alt={post.title}
            width={post.bg_image.width || 800}
            height={post.bg_image.height || 450}
            className="object-cover w-full h-full"
            loading="eager"
            priority={true}
            sizes="(max-width: 768px) 100vw, 800px"
          />
        </div>
      )}
      <h1>{post.title}</h1>
      <div className="text-white/60 text-sm sm:text-base mb-6 sm:mb-8">{post.description}</div>
      <div className="flex flex-wrap items-center gap-3 sm:gap-4 text-xs text-white/40 mb-8 sm:mb-12 pb-4 sm:pb-6 border-b border-white/10">
        <div className="flex items-center gap-2">
          <span>发布于 {new Date(post.publishedAt).toLocaleDateString('zh-CN')}</span>
          {post.updatedAt !== post.publishedAt && (
            <>
              <span>·</span>
              <span>更新于 {new Date(post.updatedAt).toLocaleDateString('zh-CN')}</span>
            </>
          )}
        </div>
        <div className="flex items-center gap-2">
          <span>·</span>
          <span className="text-emerald-400/90 font-medium">{post.category}</span>
        </div>
        <button
          onClick={() => navigator.share({ title: post.title, url: window.location.href })}
          className="ml-auto inline-flex items-center gap-2 text-white/60 hover:text-white transition-colors"
        >
          <Share2Icon className="size-4" />
          <span>分享</span>
        </button>
      </div>

      {pluginsLoaded ? (
        <ReactMarkdown
          rehypePlugins={plugins}
          components={{
            pre: ({ node, ...props }) => (
              <div className="relative group">
                <CopyButton text={node?.children[0]?.children[0]?.value} />
                <pre {...props} />
              </div>
            ),
            img: ({ node, ...props }) => (
              <Image
                src={props.src || ''}
                alt={props.alt || '博客图片'}
                width={800}
                height={450}
                className="w-full h-auto"
                loading="lazy"
                sizes="(max-width: 768px) 100vw, 800px"
              />
            )
          }}
        >
          {post.content}
        </ReactMarkdown>
      ) : (
        <div className="animate-pulse bg-white/5 h-96 rounded-md my-4"></div>
      )}
    </article>
  );
}